package com.ruoyi.project.tool.swagger.UserController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ImageUtils;
import com.ruoyi.common.utils.MutipartUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Ide;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.OperatorType;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysMobileUser;
import com.ruoyi.project.system.domain.vo.LoginVo;
import com.ruoyi.project.system.domain.vo.UserInfo;
import com.ruoyi.project.system.domain.vo.WxLoginInfo;
import com.ruoyi.project.system.service.ISysMobileUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mobileUser")
public class UserController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private ISysMobileUserService mobileUserService;

    @Autowired
    private SendUtils sendUtils;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysLoginService loginService;

    @ApiOperation("获取用户详细")
    @GetMapping("getInfo")
    public AjaxResult getUser() {
        return AjaxResult.success(SecurityUtils.getLoginUser().getSysMobileUser());
    }
    /*
    *  手机号注册
    * */
    @PostMapping(value = "/sendCode")
    @Log(title = "发送验证码", operatorType = OperatorType.MOBILE)
    @Ide
    @ApiOperation("用户注册发送验证码")
    public AjaxResult sendCode(@RequestBody Map map) {
        return sendUtils.send(map);
    }

    @PostMapping(value = "/register")
    @Log(title = "用户端注册", operatorType = OperatorType.MOBILE)
    @Ide
    @ApiOperation("用户端注册")
    @Transactional
    public AjaxResult login(@RequestBody SysMobileUser sysMobileUser) {
        if (null == sysMobileUser.getPhone()) {
            return AjaxResult.error("手机号为空");
        }
        if (null == sysMobileUser.getPassword()) {
            return AjaxResult.error("密码为空");
        }
        if (null == sysMobileUser.getCode()) {
            return AjaxResult.error("短信验证码为空");
        }
        if (null == sysMobileUser.getKey()) {
            return AjaxResult.error("验证码值为空");
        }
        String verifyKey = Constants.PHONE_CODE_KEY + sysMobileUser.getKey();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            return AjaxResult.error("验证码失效");
        }
        if (!(sysMobileUser.getCode() + "").equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误");
        }
        sysMobileUser.setPassword(SecurityUtils.encryptPassword(sysMobileUser.getPassword()));
        SysMobileUser user = mobileUserService.selectSysMobileUserByName(sysMobileUser.getPhone());
        if (null != user) {
            return AjaxResult.error("用户已存在!");
        }
        int flag = mobileUserService.insertSysMobileUser(sysMobileUser);
        if (flag == 1) {
            return AjaxResult.success("注册成功");
        }
        return AjaxResult.error("注册失败");
    }

    /**
     * 微信授权登录
     */
    @Ide
    @PostMapping("authorizedLogin")
    public AjaxResult insertMobileUser(@RequestBody WxLoginInfo wxLoginInfo) throws Exception {
        Map map = new HashMap();
        String path = "D:\\ruoyi\\uploadPath\\" + IdUtil.simpleUUID() + ".jpg";
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if ("".equals(code) || null == userInfo) {
            return AjaxResult.error("参数不正确");
        }
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxMaService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sessionKey == null || openId == null) {
            return AjaxResult.error("错误");
        }
        SysMobileUser sysMobileUser = mobileUserService.queryUserOpenId(openId);
        if (null == sysMobileUser) {
            sysMobileUser = new SysMobileUser();
            sysMobileUser.setUserName(userInfo.getNickName());
            sysMobileUser.setOpenId(openId);
            sysMobileUser.setSex(userInfo.getGender());
            sysMobileUser.setDelFlag("0");

            String avatarUrl = ImageUtils.downloadPicture(userInfo.getAvatarUrl(), path);
            MultipartFile mulFile = MutipartUtils.getMulFileByPath(avatarUrl);
            sysMobileUser.setImage(MutipartUtils.uploadFile(mulFile));
//          UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysMobileUser.getUserName(), openId);
//          String token = loginService.loginMobile(sysMobileUser.getUserName(),openId);

            mobileUserService.insertSysMobileUser(sysMobileUser);
            LoginUser loginUser = new LoginUser();
            loginUser.setSysMobileUser(mobileUserService.selectSysMobileUserById(sysMobileUser.getMobileUserId()));
            loginUser.setUserName(sysMobileUser.getUserName());
            loginUser.setPassword(openId);
            String token = tokenService.createToken(loginUser);
            userInfo.setMobileUserId(sysMobileUser.getMobileUserId());
            map.put("token", token);
            map.put("userInfo", userInfo);
            return AjaxResult.success(map);

        } else {
//          UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysMobileUser.getUserName(), openId);
//          String token = loginService.loginMobile(sysMobileUser.getUserName(),openId);
            LoginUser loginUser = new LoginUser();
            loginUser.setSysMobileUser(mobileUserService.selectSysMobileUserById(sysMobileUser.getMobileUserId()));
            loginUser.setUserName(sysMobileUser.getUserName());
            loginUser.setPassword(openId);
            String token = tokenService.createToken(loginUser);
            userInfo.setMobileUserId(sysMobileUser.getMobileUserId());
            map.put("token", token);
            map.put("userInfo", userInfo);
            return AjaxResult.success(map);
        }
    }

    @PostMapping(value = "/loginMobile")
    @Log(title = "用户端登录", operatorType = OperatorType.MOBILE)
    @Ide
    @ApiOperation("用户手机号或者用户名登录")
    public AjaxResult login(@RequestBody LoginVo vo) {
      Object token = loginService.loginMobile(vo.getUsername(), vo.getPassword());
      return AjaxResult.success(token);
    }

    @PostMapping(value = "/enterpriseMobile")
    @Log(title = "企业端登录", operatorType = OperatorType.MOBILE)
    @Ide
    @ApiOperation("用户手机号或者用户名登录")
    public AjaxResult enterpriseLogin(@RequestBody LoginVo vo) {
        Object token = loginService.userlogin(vo.getUsername(), vo.getPassword(),null,null);
        return AjaxResult.success(token);
    }

    @PostMapping(value = "/codeLogin")
    @Log(title = "动态验证码登录", operatorType = OperatorType.MOBILE)
    @Ide
    @ApiOperation("动态验证码登录")
    public AjaxResult codeLogin(@RequestBody Map map) {
        if (null == map.get("phone")) {
            return AjaxResult.error("手机号为空");
        }
        if (null == map.get("code")) {
            return AjaxResult.error("短信验证码为空");
        }
        if (null == map.get("key")) {
            return AjaxResult.error("验证码值为空");
        }
        String verifyKey = Constants.PHONE_CODE_KEY + map.get("key");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            return AjaxResult.error("验证码失效");
        }
        if (!(map.get("code") + "").equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误");
        }
        if("1".equals(map.get("type"))){
            SysMobileUser sysMobileUser = mobileUserService.selectSysMobileUserByName(map.get("phone") + "");
            if (null == sysMobileUser) {
                return AjaxResult.success("手机号尚未注册!");
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setSysMobileUser(sysMobileUser);
            loginUser.setUserName(sysMobileUser.getUserName());
            Object token = tokenService.createToken(loginUser);
            return AjaxResult.success(token);
        }else{
            SysMobileUser sysMobileUser = mobileUserService.selectByName(map.get("phone") + "");
            if (null == sysMobileUser) {
                return AjaxResult.success("手机号尚未注册!");
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setSysMobileUser(sysMobileUser);
            loginUser.setUserName(sysMobileUser.getUserName());
            Object token = tokenService.createToken(loginUser);
            return AjaxResult.success(token);
        }
    }
}
